package com.ayic.garbagerecycle.service.impl;

import com.ayic.garbagerecycle.pojo.Result;
import com.ayic.garbagerecycle.pojo.WasteRecord;
import com.ayic.garbagerecycle.service.UserService;
import com.ayic.garbagerecycle.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Integer getUserIdByUsername(String username) {
        return userMapper.getUserIdByUsername(username);
    }

    @Override
    public Result getUserInfo(String username) {
        return Result.success(userMapper.selectUserByName(username));
    }

    @Override
    public Result updatePassword(String username, String newPassword) {
        int updateCount = userMapper.updatePassword(username, newPassword);
        if (updateCount > 0) {
            return Result.success("密码更新成功");
        } else {
            return Result.error("密码更新失败");
        }
    }

    @Override
    public Result updateEmail(String username, String newEmail) {
        int updateCount = userMapper.updateEmail(username, newEmail);
        if (updateCount > 0) {
            return Result.success("邮箱更新成功");
        } else {
            return Result.error("邮箱更新失败");
        }
    }

    @Override
    public Map<String, Integer> getUserRecInfo(int userId) {
        List<Map<String, Object>> list = userMapper.countWasteTypesByUserId(userId);
        Map<String, Integer> result = new HashMap<>();
        for (Map<String, Object> map : list) {
            String typeName = (String) map.get("waste_type_name");
            Integer count = ((Number) map.get("count")).intValue();
            result.put(typeName, count);
        }
        return result;
    }

    @Override
    public Result getUserWasteRec(int userId) {
        List<WasteRecord> wasteRecords= userMapper.selectWasteRecordsByUserId(userId);
        return Result.success(wasteRecords);
    }

}